package com.yanqu.road.entity.activity.coupon;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.entity.DataObject;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.TimeHelper;
import com.yanqu.road.utils.date.DateHelper;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CouponActivityUserData extends DataObject {
    private long userId;                //玩家编号
    private int activityId;             //活动编号
    private Map<Integer, CouponTrigger> couponTriggerMap = new ConcurrentHashMap<>();       //触发数据

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        if(this.userId != userId) {
            this.userId = userId;
            setUpdateOption();
        }
    }

    public int getActivityId() {
        return activityId;
    }

    public void setActivityId(int activityId) {
        if(this.activityId != activityId) {
            this.activityId = activityId;
            setUpdateOption();
        }
    }

    public String getCouponTriggerMapJsonStr(){
        if(null == couponTriggerMap){
            return "{}";
        }else {
            return JSON.toJSONString(couponTriggerMap);
        }
    }

    public Map<Integer, CouponTrigger> getCouponTriggerMap() {
        return couponTriggerMap;
    }

    public void setCouponTriggerMap(Map<Integer, CouponTrigger> couponTriggerMap) {
        this.couponTriggerMap = couponTriggerMap;
    }

    public int getCouponTriggerTimes(int type){
        CouponTrigger data = couponTriggerMap.get(type);
        if(null == data){
            return 0;
        }
        return data.getTriggerTimes();
    }

    public void addCouponTriggerTimes(int type, int times){
        if(!couponTriggerMap.containsKey(type)){
            synchronized (couponTriggerMap){
                if(!couponTriggerMap.containsKey(type)){
                    CouponTrigger data = new CouponTrigger();
                    data.setType(type);
                    data.setTriggerTimes(0);
                    data.setResetTime(System.currentTimeMillis());
                    couponTriggerMap.put(type, data);
                }
            }
        }
        CouponTrigger data = couponTriggerMap.get(type);
        if(null != data){
            synchronized (data){
                data.setTriggerTimes(data.getTriggerTimes() + times);
            }
            setUpdateOption();
        }
    }

    public void dailyReset(){
        for(CouponTrigger data : couponTriggerMap.values()){
            if(DateHelper.isSameMonth(data.getResetTime())){
                continue;
            }
            synchronized (data){
                if(DateHelper.isSameMonth(data.getResetTime())){
                    continue;
                }
                data.setTriggerTimes(0);
                data.setResetTime(System.currentTimeMillis());
            }
        }
    }
}
